//
//  ARSegmentPageController.m
//  ARSegmentPager
//
//  Created by August on 15/3/28.
//  Copyright (c) 2015年 August. All rights reserved.
//

#import "ARSegmentPageController.h"


@interface ARSegmentPageController ()

@property (nonatomic, strong) NSMutableArray *controllers;
@property (nonatomic, strong) UIColor *segmentColor;
@property (nonatomic, assign) NSInteger segmentHeight;

@end

@implementation ARSegmentPageController



- (id)initWithSegmentHeight:(NSInteger)segmentHeight segmentColor:(UIColor *)color viewControllers:(NSMutableArray *)viewControllers{
    
    if( self = [super init] ){
        self.segmentHeight = segmentHeight;
        self.segmentColor = color;
        self.controllers = viewControllers;
    }
    
    return self;
}


-(void)viewDidLoad {
    [super viewDidLoad];
    
    UISegmentedControl *segmentedControl = [[UISegmentedControl alloc]initWithFrame:CGRectMake(5, UI_HIGHT_NAVIGATION_BAR + UI_HIGHT_STATUS_BAR + 10, ZYAppWidth - 10, self.segmentHeight)];
    [segmentedControl addTarget:self action: @selector(controlPressed:) forControlEvents: UIControlEventValueChanged];
    segmentedControl.tintColor = self.segmentColor;
    
    self.tabSheets = segmentedControl;
    
    
    [self.controllers enumerateObjectsUsingBlock:^(UIViewController *controller, NSUInteger idx, BOOL *stop) {
        NSString *title = [controller title];
        [self.tabSheets insertSegmentWithTitle:title
                                       atIndex:idx
                                      animated:NO];
    }];
    [self.view addSubview:self.tabSheets];
    self.tabSheets.selectedSegmentIndex = 0;
    UIViewController *controller = self.controllers[0];
    [controller willMoveToParentViewController:self];
    [self.view insertSubview:controller.view atIndex:0];
    [self addChildViewController:controller];
    [controller didMoveToParentViewController:self];
 
}

- (void) controlPressed:(id)sender {
    
    NSInteger selectedSegment = self.tabSheets.selectedSegmentIndex;
    
    UIViewController *controller = self.controllers[selectedSegment];
    [controller willMoveToParentViewController:self];
    [self.view insertSubview:controller.view atIndex:0];
    [self addChildViewController:controller];
    [controller didMoveToParentViewController:self];
    
}


@end
